package com.tonglin.red.controller;

import com.tonglin.red.entity.vo.RedPacketDto;
import com.tonglin.red.service.IRedPacketService;
import com.tonglin.red.util.BaseResponse;
import com.tonglin.red.util.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.math.BigDecimal;

@RestController
public class RedPacketController {
    @Autowired
    IRedPacketService iRedPacketService;
    //定义日志
    private static final Logger log = LoggerFactory.getLogger(RedPacketController.class);
    //定义请求路径的前缀
    private static final String prefix = "red/packet";
    //注入红包业务逻辑处理接口服务
    /**
     * 发红包请求，请求方法为POSt，请求参数采用JSON格式进行提交
     *
     */
    @PostMapping(value = prefix+"/hand/out",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse handout(@Validated @RequestBody RedPacketDto dto, BindingResult result){
        //参数校验
        if (result.hasErrors()){
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try{
            //核心业务逻辑处理服务，最终返回红包全局唯一标识符
            String redId = iRedPacketService.handOut(dto);
            response.setData(redId);
        } catch (Exception e) {
            //如果报异常则输出日志并返回响应的错误信息
            log.error("发红包发生异常：dto{}",dto,e.fillInStackTrace());
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
            e.printStackTrace();
        }

        return response;
    }

    @GetMapping(prefix+"/rob")
    public BaseResponse rob(@RequestParam Integer userId,@RequestParam String redId){
        //定义响应对象
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            //调用红包业务逻辑接口中的方法，最终返回抢到的红包金额
            //单位为元（不为null时表示抢到了，否则代表已经抢完了）
            BigDecimal result = iRedPacketService.rob(userId,redId);
            if (result!=null){
                //将抢到的红包返回前端
                response.setData(result);
            }else {
                //没有抢到红包，红包已经抢完了
                response=new BaseResponse(StatusCode.Fail.getCode(),"红包已经抢完了！");
            }
        } catch (Exception e) {
            //处理过程中如果发生异常，则输出异常信息并返回信息给前端
            log.error("抢红包异常：userId={} redId={}",userId,redId,e.fillInStackTrace());
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());

        }
        //返回结果给前端
        return response;
    }

}
